// pages/userConsole/userConsole.js
import Notify from '../../dist/notify/notify';
const db = wx.cloud.database()
const app = getApp()
Page({

  data: {
    shows: false,
    showInputForm: false, // 控制输入表单弹窗显示
    minDate: new Date().getTime()-864000000,
    defaultdate:new Date().getTime(),
    maxDate:new Date().getTime(),
    loading:false,
    activeTab: 0, // 当前激活的标签页索引：0-支出，1-收入
    actions: [
      {
        name: '支出',
      },
      {
        name: '收入',
      },
    ],
    typedata: [
      {
        name: '餐饮',
        icon: '../../icon/food.png',
        active: false
      },
      {
        name: '交通',
        icon: '../../icon/jiaotong.png',
        active: false
      },
      {
        name: '住房',
        icon: '../../icon/housing.png',
        active: false
      },
      {
        name: '美容',
        icon: '../../icon/meirong.png',
        active: false
      },
      {
        name: '服装',
        icon: '../../icon/fushilei.png',
        active: false
      },
      {
        name: '旅游',
        icon: '../../icon/lvyou.png',
        active: false
      },
      {
        name: '娱乐',
        icon: '../../icon/yule.png',
        active: false
      },
      {
        name: '医疗',
        icon: '../../icon/yiliao.png',
        active: false
      },
      {
        name: '通讯',
        icon: '../../icon/tongxun.png',
        active: false
      },
      {
        name: '学习',
        icon: '../../icon/xuexi.png',
        active: false
      },
      {
        name: '数码',
        icon: '../../icon/shumapeijian.png',
        active: false
      },
      {
        name: '其他',
        icon: '../../icon/qita.png',
        active: false
      }
    ],
    typedatas: [
      {
        name: '工资',
        icon: '../../icon/gongzi.png',
        active: false
      },
      {
        name: '兼职',
        icon: '../../icon/jianzhi.png',
        active: false
      },
      {
        name: '礼金',
        icon: '../../icon/lijin.png',
        active: false
      },
      {
        name: '奖金',
        icon: '../../icon/jiangjin.png',
        active: false
      },
      {
        name: '其他',
        icon: '../../icon/qita.png',
        active: false
      }
    ],
    show: false,
    date: '',
    message: '',
    money: '',
    expenditure: true,
    _openid: "",
    type: 0,
    recordtype: '',
    icondata:'',
    steppervalue:'',
    // 游客模式相关
    isGuest: false,
    showGuestTip: false
  },
  onLoad: function () {
    let that = this
    wx.cloud.callFunction({
      name: "login",
      complete: res => {
        this.setData({ _openid: res.result.openid });
      }
    })
  },
  onShow: function (options) {
    // 更新自定义tabBar选中状态
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 2
      })
    }
    
    // 检查登录状态
    const userId = wx.getStorageSync('id');
    if (!userId) {
      wx.redirectTo({
        url: '../login/login'
      });
      return;
    }
    
    // 检查游客模式
    const isGuest = app.globalData.isGuest || wx.getStorageSync('isGuest');
    
    // 设置默认日期为当天
    const today = new Date();
    const todayStr = this.formatDate(today.getTime());
    
    // 加载自定义类别
    this.loadCustomCategories();
    
    this.setData({
      isGuest: isGuest,
      showGuestTip: isGuest,
      shows: false,
      date: todayStr, // 设置默认日期为当天
      message:'',
      money: '', // 设置为空字符串，使用户输入时直接替换
      steppervalue: '', // 设置为空字符串，使用户输入时直接替换
      type: '0', // 默认为支出
      expenditure: true,
      activeTab: 0 // 默认显示支出标签页
    });
    
    if (isGuest) {
      app.globalData.isGuest = true;
    }
  },
  onSelect(event) {

    if (event.detail.name) {

      if (event.detail.name == '支出') {
        this.setData({ shows: false, expenditure: true, type: 0 });
      } else {
        this.setData({ shows: false, expenditure: false, type: 1 });
      }
    } else {
      return
    }
  },
  
  // 切换标签页
  switchTab(event) {
    const index = parseInt(event.currentTarget.dataset.index);
    const type = index === 0 ? '0' : '1';
    
    this.setData({
      activeTab: index,
      type: type,
      expenditure: type == '0',
      recordtype: '', // 清空已选择的类型
      icondata: ''
    });
    
    // 重置所有类型按钮的选中状态
    let typedata = this.data.typedata.map(item => ({...item, active: false}));
    let typedatas = this.data.typedatas.map(item => ({...item, active: false}));
    this.setData({
      typedata: typedata,
      typedatas: typedatas
    });
  },
  
  // 滑动切换
  swiperChange(event) {
    const index = event.detail.current;
    const type = index === 0 ? '0' : '1';
    
    this.setData({
      activeTab: index,
      type: type,
      expenditure: type == '0',
      recordtype: '', // 清空已选择的类型
      icondata: ''
    });
    
    // 重置所有类型按钮的选中状态
    let typedata = this.data.typedata.map(item => ({...item, active: false}));
    let typedatas = this.data.typedatas.map(item => ({...item, active: false}));
    this.setData({
      typedata: typedata,
      typedatas: typedatas
    });
  },
  ceshi(event) {
    let that = this
    console.log(event.currentTarget.dataset.message)
    that.setData({ 
      recordtype: event.currentTarget.dataset.message,
      icondata: event.currentTarget.dataset.icon,
      showInputForm: true, // 显示输入表单弹窗
      money: '', // 设置为空字符串，使用户输入时直接替换
      steppervalue: '' // 设置为空字符串，使用户输入时直接替换
    });
    let typelist = that.data.type == '0'?that.data.typedata:that.data.typedatas
    for (var i = 0; i < typelist.length; i++) {
      typelist[i].active = false;
      that.data.type == '0'?that.setData({ typedata: typelist }):that.setData({ typedatas: typelist })
      if (typelist[i].name == event.currentTarget.dataset.message) {
        typelist[i].active = true;
        that.data.type == '0'?that.setData({ typedata: typelist }):that.setData({ typedatas: typelist })
      }
    }
  },
  calendar() {
    this.setData({
      show: true
    });
  },
  onDisplay() {
    this.setData({ show: true });
  },
  onClose() {
    this.setData({ show: false });
  },
  formatDate(date) {
    const dt = new Date(date);
    const y = dt.getFullYear();
    const m = (dt.getMonth() + 1 + "").padStart(2, "0");
    const d = (dt.getDate() + "").padStart(2, "0");
    return `${y}-${m}-${d}`;
  },
  onConfirm(event) {
    this.setData({
      show: false,
      date: this.formatDate(event.detail),
    });
  },
  onInput(event) {
    this.setData({
      currentDate: event.detail,
    });
  },
  onChange(event) {
    // 如果输入值为0，则将money和steppervalue设置为空字符串
    const value = event.detail === 0 ? '' : event.detail;
    this.setData({ 
      money: value,
      steppervalue: value
    });
  },
  magdata(e){
    this.setData({ message: e.detail });
  },
  // 关闭输入表单弹窗
  closeInputForm() {
    this.setData({
      showInputForm: false
    });
  },
  
  preservation() {
    const typeText = this.data.type == '0' ? '支出' : '收入';
    if (!this.data.recordtype) {
      Notify({ type: 'warning', message: `请选择${typeText}类型哦！` });
    } else if (!this.data.money) {
      Notify({ type: 'warning', message: '请输入金额哦！' });
    }else {
      this.setData({ loading: true});
      let postdata = {
        type: this.data.type,
        recordtype: this.data.recordtype,
        date: this.data.date,
        remarks: this.data.message,
        money: this.data.type == '0'?this.data.money*-1: Number(this.data.money),
        userid: wx.getStorageSync('id'),
        icon:this.data.icondata,
        _id: Date.now() + '_' + Math.random().toString(36).substr(2, 9) // 生成唯一ID
      }
      console.log(postdata)
      
      // 检查是否为游客模式
      const isGuest = wx.getStorageSync('isGuest')
      
      if (isGuest) {
        // 游客模式：保存到本地存储
        try {
          let localRecords = wx.getStorageSync('guestRecords') || []
          localRecords.push(postdata)
          wx.setStorageSync('guestRecords', localRecords)
          // 重置表单，日期重置为当天，备注重置为空，金额重置为0
          const today = new Date();
          const todayStr = this.formatDate(today.getTime());
          this.setData({ 
            loading: false,
            shows: false,
            showInputForm: false,
            date: todayStr,
            message: '',
            money: '',
            steppervalue: ''
          });
          // 设置数据更新标志，通知其他页面刷新
          wx.setStorageSync('dataUpdated', true);
          Notify({ type: 'success', message: '增加成功（游客模式）' });
          
          // 延迟跳转到bill页面，让用户看到成功提示
          setTimeout(() => {
            wx.switchTab({
              url: '/pages/bill/bill'
            });
          }, 1500);
        } catch (e) {
          console.error('游客模式保存失败：', e)
          this.setData({ loading: false });
          Notify({ type: 'danger', message: '保存失败，请重试' });
        }
      } else {
        // 正常用户：保存到云数据库
        db.collection('record').add({
          data: postdata
        }).then(res => {
          // 重置表单，日期重置为当天，备注重置为空，金额重置为0
          const today = new Date();
          const todayStr = this.formatDate(today.getTime());
          this.setData({ 
            loading: false,
            shows: false,
            showInputForm: false,
            date: todayStr,
            message: '',
            money: '',
            steppervalue: ''
          });
          // 设置数据更新标志，通知其他页面刷新
          wx.setStorageSync('dataUpdated', true);
          Notify({ type: 'success', message: '增加成功' });
          
          // 延迟跳转到bill页面，让用户看到成功提示
          setTimeout(() => {
            wx.switchTab({
              url: '/pages/bill/bill'
            });
          }, 1500);
        }).catch(err => {
          console.error('保存到云数据库失败：', err)
          this.setData({ loading: false });
          Notify({ type: 'danger', message: '保存失败，请重试' });
        })
      }
    }

  },

  // 加载自定义类别
  loadCustomCategories() {
    const customCategories = wx.getStorageSync('customCategories') || [];
    const hiddenCategories = wx.getStorageSync('hiddenCategories') || [];
    
    const allDefaultTypeData = [
      {
        id: 'default_1',
        name: '餐饮',
        icon: '../../icon/food.png',
        active: false
      },
      {
        id: 'default_2',
        name: '交通',
        icon: '../../icon/jiaotong.png',
        active: false
      },
      {
        id: 'default_3',
        name: '住房',
        icon: '../../icon/housing.png',
        active: false
      },
      {
        id: 'default_4',
        name: '美容',
        icon: '../../icon/meirong.png',
        active: false
      },
      {
        id: 'default_5',
        name: '服装',
        icon: '../../icon/fushilei.png',
        active: false
      },
      {
        id: 'default_6',
        name: '旅游',
        icon: '../../icon/lvyou.png',
        active: false
      },
      {
        id: 'default_7',
        name: '娱乐',
        icon: '../../icon/yule.png',
        active: false
      },
      {
        id: 'default_8',
        name: '医疗',
        icon: '../../icon/yiliao.png',
        active: false
      },
      {
        id: 'default_9',
        name: '通讯',
        icon: '../../icon/tongxun.png',
        active: false
      },
      {
        id: 'default_10',
        name: '学习',
        icon: '../../icon/xuexi.png',
        active: false
      },
      {
        id: 'default_11',
        name: '数码',
        icon: '../../icon/shumapeijian.png',
        active: false
      },
      {
        id: 'default_12',
        name: '其他',
        icon: '../../icon/qita.png',
        active: false
      }
    ];
    
    // 过滤掉被隐藏的默认类别
    const defaultTypeData = allDefaultTypeData.filter(category => !hiddenCategories.includes(category.id));
    
    // 将自定义类别转换为typedata格式并添加到默认类别中
    const customTypeData = customCategories.map(category => ({
      name: category.name,
      icon: this.getCustomIconPath(category.icon),
      active: false,
      isCustom: true
    }));
    
    // 合并默认类别和自定义类别
    const mergedTypeData = [...defaultTypeData, ...customTypeData];
    
    this.setData({
      typedata: mergedTypeData
    });
  },
  
  // 获取自定义图标路径
  getCustomIconPath(iconFileName) {
    // 根据图标文件名判断所属分类文件夹
    const jiaotongIcons = [
      'a-busgongjiaochegonggongqichekechejiaotonggongju.png',
      'a-ditiejiaotonggongju.png',
      'a-taxichuzucheqichexiaochejiaotonggongju.png',
      'jiaotonggongju1.png',
      'jiaotonggongju2.png',
      'jiaotonggongju4.png',
      'jiaotong.png'
    ];
    
    const yinshiIcons = [
      'Pear.png',
      'a-2-58.png',
      'chicken-meat.png',
      'shiwuqimin.png',
      'shiwuqimin_1.png',
      'food.png'
    ];
    
    const yuleIcons = [
      '-yule.png',
      'ertongyule.png',
      'tiyu.png',
      'yule3.png',
      'yule_1.png',
      'yule_2.png',
      'lvyou.png',
      'shumapeijian',
      'yule.png'

    ];
    
    const shenghuoIcons = [
      'fushilei.png',
      'housing.png',
      'meirong.png',
      'tongxun.png'
    ];
    
    const shouruIcons = [
      'jiage.png',
      'qian.png',
      'qianbi.png',
      'rp1.png',
      'shourulaiyuanguanli.png',
      'zongbaoe.png'
    ];
    
    if (jiaotongIcons.includes(iconFileName)) {
      return `/icon/images/jiaotong/${iconFileName}`;
    } else if (yinshiIcons.includes(iconFileName)) {
      return `/icon/images/yinshi/${iconFileName}`;
    } else if (yuleIcons.includes(iconFileName)) {
      return `/icon/images/yule/${iconFileName}`;
    } else if (shenghuoIcons.includes(iconFileName)) {
      return `/icon/images/shenghuo/${iconFileName}`;
    } else if (shouruIcons.includes(iconFileName)) {
      return `/icon/images/shouru/${iconFileName}`;
    }
    
    // 默认返回交通分类路径
    return `/icon/images/jiaotong/${iconFileName}`;
  },

  // 打开设置页面
  openSettings() {
    const type = this.data.type === '0' ? 'expense' : 'income';
    wx.navigateTo({
      url: `/pages/custom-category/custom-category?type=${type}`
    });
  }

})